$(function () {
    var loading = $('#loading');
    var toggleLoading = function (isShow) {
        if (isShow) {
            loading.removeClass('hidden');
        } else {
            loading.addClass('hidden');
        }
    };

    var tip = function (obj, info) {
        obj.tip({
            content: info,
            background: "#000",
            color: "#fff"
        });
    };
    var refreshLayout = function (datas) {
        var customerInfos = datas.item;
        if (customerInfos.length === 0) {
            $('#customerListBody').html('');
            $('#customerListBodyEmpty').removeClass('hidden');
            $('#customerListPage').addClass('hidden');
        } else {
            $('#customerListBodyEmpty').addClass('hidden');
            var templateHTML = $($('#templateCustomer').clone().html());
            var customerHTML = '';
            $.each(customerInfos, function (key, customerInfo) {
                templateHTML.find('.vip-name').html(customerInfo.name);
                templateHTML.find('.vip-level').html(customerInfo.vipname);
                if(customerInfo.mobile){
                   templateHTML.find('.vip-mobile').html('+'+customerInfo.areaCode+'&nbsp;'+customerInfo.mobile); 
                }
                templateHTML.find('.vip-identity').html(customerInfo.identity);
                templateHTML.find('.vip-time').html(customerInfo.checkin);
                //templateHTML.find('.vip-total').html((parseFloat(customerInfo.receipt)+parseFloat(customerInfo.deposit)).toFixed(2));
                templateHTML.find('.vip-total').html(parseFloat(customerInfo.receipt).toFixed(2));
                templateHTML.find('.vip-detail').attr('vipUserId',customerInfo.id);
                templateHTML.find('.vip-recharge').attr('vipUserId',customerInfo.id);
                templateHTML.find('.vip-balance').html(customerInfo.cardPrice);
                customerHTML += templateHTML.prop('outerHTML');
            });
            $('#customerListBody').html(customerHTML);
            $('[data-toggle="tooltip"]').tooltip();
            var pageInfo = datas.page;
            var currentPage = parseInt(pageInfo.currentPage);
            var pages = parseInt(pageInfo.total);
            var pageContainer = $('#customerListPage');
            pageContainer.removeClass('hidden');
            var pageHTML = '';
            var templatePage = $($('#templatePage').clone().html());
            for (var i = 1; i <= pages; i++) {
                if (currentPage === i) {
                    templatePage.addClass('active');
                } else {
                    templatePage.removeClass('active');
                }
                templatePage.find('a').html(i).attr('data-value', i);
                pageHTML += templatePage.prop('outerHTML');
            }
            pageContainer.find('.pagination').html(pageHTML);
            pageContainer.find('.page-count').html(pages);
            pageContainer.find('.page-total').html(pageInfo.totalCount);
        }
    };

    var requestInfo = function (page, mobile, submitBtn, vipInfoId, allHotel) {
        window.lastRequestMobile = mobile;
        toggleLoading(true);
        var params = {
            'hotel': window.currentHotel,
            'currentPage': page,
        };
        if (mobile !== '') {
            params.mobile = mobile;
        }
        if (vipInfoId !== '') {
            params.vipInfoId = vipInfoId;
        }
        if (allHotel !== '') {
            params.allHotel = allHotel;
        }
        ajaxRequest('/Home/Customer/vip', params, 'post', function (data) {
            toggleLoading(false);
            window.serverDatas = data.data;
            refreshLayout(window.serverDatas);
        }, function (error, obj) {
            toggleLoading(false);
            if (typeof error.responseJSON == 'undefined') {
                tip(obj, lang('tip.system'));
                return;
            }

            tip(obj, error.responseJSON.info);
        }, submitBtn);
    };

    requestInfo(1, '', $('#filterSearch'));
    window.filterMobile = '';
    $('#customerListPage .pagination').on('click', 'li:not(.active) a', function () {
        var pageIndex = $(this).data('value');
        var submitBtn = $('#filterSearch');
        requestInfo(pageIndex, window.filterMobile, $('#filterSearch'));
    });

    //号码搜索
    $('#filterSearch').on('click', function(e) {
        e.preventDefault();
        window.filterMobile = $('#filterMobile').val().trim();
        var allHotel = $('#search-hotel-info').data('allHotel');
        var submitBtn = $(this);
        if (filterMobile !== '' && !window.commonRegexp.mobile.test(filterMobile)) {
            tip($('#filterMobile'), lang('tip.mobile'));
            return;
        }
        requestInfo(1, window.filterMobile, submitBtn, '', allHotel);
    });

    //等级搜索
    $('#search-level').find('li').on('click', function(e) {
        e.preventDefault();
        var submitBtn = $(this);
        var allHotel = $('#search-hotel-info').data('allHotel');
        if($(this).hasClass('active')){
            $(this).removeClass('active');
            $('#search-level-info').text(lang('grade'));
            var vipInfoId = '';
            $('#search-level-info').data('vipInfoId','');
        }else{
            $(this).addClass('active').siblings().removeClass('active');
            var levelName = $(this).find('a').text();
            var vipInfoId = $(this).attr('data-value');
            $('#search-level-info').text(levelName);
            $('#search-level-info').data('vipInfoId',vipInfoId);
        }
        
        requestInfo(1, '', submitBtn, vipInfoId, allHotel);
    });
    
    //酒店搜索
    $('#search-hotel').find('li').on('click', function(e) {
        e.preventDefault();
        var submitBtn = $(this);
        var vipInfoId = $('#search-level-info').data('vipInfoId');
        if($(this).hasClass('active')){
            $(this).removeClass('active');
            $('#search-hotel-info').text(lang('liveTimes'));
            var allHotel = '';
            $('#search-hotel-info').data('allHotel','');
        }else{
            $(this).addClass('active').siblings().removeClass('active');
            var hotelName = $(this).find('a').text();
            var allHotel = '1';
            $('#search-hotel-info').text(hotelName);
            $('#search-hotel-info').data('allHotel','1');
        }
        
        requestInfo(1, '', submitBtn, vipInfoId, allHotel);
    });


    $('#addBirthday').datepicker({
        format: 'yyyy-mm-dd',
        language: "zh-CN",
        autoclose: true,
    });
    $('#add-vip-modal').click(function (){
        $('#add-vip-info').text('');
    });
    $('#add-vip').on('click', function(e) {
        e.preventDefault();
        var me = $(this);
        
        var params = {
            hotel: window.currentHotel,
            name: $.trim($('#addName').val()),
            mobile: $.trim($('#addMobile').val()),
            vipInfoId: $('#addLevel').val(),
            gender: $('#addGender').val(),
            birthday: $('#addBirthday').val(),
            nation: $.trim($('#addNation').val()),
            identity: $.trim($('#addIdentity').val()),
            address: $.trim($('#addAddress').val()),
            wechat: $.trim($('#addWechat').val()),
            remark: $.trim($('#addRemark').val()),
            share: $(this).attr('data-share'),
            areaCode : $('#add-vip-form .areaCodeValue').text().trim(),
            vipLevelName: $('#addLevel').find("option:selected").text(),
        };
        if(params.name.length == 0){
            $('#add-vip-info').text(lang('vip.name'));
            return false;
        }
        if(params.mobile.length == 0){
            $('#add-vip-info').text(lang('vip.mobile'));
            return false;
        }
        if(params.mobile !== '' && !window.commonRegexp.mobile.test(params.mobile)){
            $('#add-vip-info').text(lang('vip.mobileWrong'));
            return false;
        }
        if(params.identity !== '' && !window.commonRegexp.IDCard.test(params.identity)){
            $('#add-vip-info').text(lang('vip.identity'));
            return false;
        }
        ajaxRequest('/Home/Customer/addVip', params, 'post', function(data, submitBtn) {
            $('#addVipModel').modal('hide');
            requestInfo(1, '', $('#filterSearch'));
            $('#add-vip-form')[0].reset();
        }, function(error, submitBtn, defaultErrorHandler) {
            var errorInfo = error.responseJSON.info;
            $('#add-vip-info').text(errorInfo); 
        }, me);
    });
    $(document).on('click','.vip-detail',function(){
        $('#edit-vip-info').text(''); 
        $('#editVipActive').attr('class',"guestnone");
        $('#editVipActive').find('input').prop('disabled',true);
        $('#editVipActive').find('textarea').prop('disabled',true);
        $('#editVipActive').find('.vip-dropdown').addClass('disabled');
        $('#edit-vip').text(lang('vip.compile'));
        $('#edit-vip').data('edit','0');
        var me = $(this);
        var params = {
            hotel: window.currentHotel,
            vipUserId: $(this).attr('vipUserId'), 
        };
        ajaxRequest('/Home/Customer/setVip', params, 'post', function(data, submitBtn) {
                var vipInfo = data.data;
                $('#editName').val(vipInfo.name);
                $('#editMobile').val(vipInfo.mobile);
                $('#editVipActive').find('.areaCode .areaCodeValue').text(vipInfo.areaCode+' ');
                $('#editBirthday').val(vipInfo.birthday);
                $('#editNation').val(vipInfo.nation);
                $('#editIdentity').val(vipInfo.identity);
                $('#editAddress').val(vipInfo.address);
                $('#editWechat').val(vipInfo.wechat);
                $('#editRemark').val(vipInfo.remark);
                $('#guestdetail').data('data-id',vipInfo.id);
                $("#dropdown-level-ul").children().each(function (key) {
                    if($(this).attr('data-value') == vipInfo.vipinfo_id){
                        $(this).addClass('active');
                        var levelName = $(this).find('a').text();
                        $('#level-info').text(levelName);
                        $("#dropdown-level-ul").data('level',$(this).attr('data-value'));
                        $("#dropdown-level-ul").data('levelName',levelName);
                        $(this).siblings().removeClass('active');
                        return false;
                    } 
                })
                $("#dropdown-gender-ul").children().each(function (key) {
                    if($(this).attr('data-value') == vipInfo.gender){
                       $(this).addClass('active');
                       $('#gender-info').text($(this).find('a').text());
                       $("#dropdown-gender-ul").data('gender',$(this).attr('data-value'));
                       $(this).siblings().removeClass('active');
                       return false;
                    }
                })
                if(vipInfo.detail.length != 0){
                    var templateHTML = $($('#templateOrder').clone().html());
                    var orderHTML = '';
                    $.each(vipInfo.detail, function (key, orderInfo) {
                        templateHTML.find('.date').html(orderInfo.date);
                        templateHTML.find('.time').html(orderInfo.time);
                        templateHTML.find('.from').html(orderInfo.room);
                        templateHTML.find('.by').html(orderInfo.name);
                        templateHTML.find('.price-info').html(lang('vip.pay')+window.symbols+orderInfo.orig+lang('vip.youhui')+window.symbols+orderInfo.payment);
                        orderHTML += templateHTML.prop('outerHTML');
                    });
                    $('#orderRecordContainer').html(orderHTML);
                } else {
                    $('#orderRecordContainer').html(lang('vip.noExpense'));
                }

            }, function(error, submitBtn, defaultErrorHandler) {
                var errorInfo = error.responseJSON.info;
                $('#add-vip-info').text(errorInfo); 
        }, me);
    });
    
    $("#dropdown-level-ul").children().click(function (key) {
            $(this).addClass('active');
            var levelName = $(this).find('a').text();
            $('#level-info').text(levelName);
            $(this).siblings().removeClass('active');
            $("#dropdown-level-ul").data('level',$(this).attr('data-value'));
            $("#dropdown-level-ul").data('levelName',levelName);
    });
    $("#dropdown-gender-ul").children().click(function (key) {
            $(this).addClass('active');
            $('#gender-info').text($(this).find('a').text());
            $(this).siblings().removeClass('active');
            $("#dropdown-gender-ul").data('gender',$(this).attr('data-value'));
    })
    $('#editBirthday').datepicker({
        format: 'yyyy-mm-dd',
        language: "zh-CN",
        autoclose: true,
    });
    $('#edit-vip').click(function(){
        $('#editVipActive').attr('class',"guestedit");
        $('#editVipActive').find('input').prop('disabled',false);
        $('#editVipActive').find('textarea').prop('disabled',false);
        $('#editVipActive').find('.vip-dropdown').removeClass('disabled');
        var me = $(this);
        me.text(lang('vip.save'));
        //转换按键状态
        if(me.data('edit')=='0') {
            me.data('edit','1');
            return false;
        }

        var params = {
            hotel: window.currentHotel,
            vipUserId: $('#guestdetail').data('data-id'),
            name: $.trim($('#editName').val()),
            mobile: $.trim($('#editMobile').val()),
            vipInfoId: $("#dropdown-level-ul").data('level'),
            gender: $("#dropdown-gender-ul").data('gender'),
            birthday: $('#editBirthday').val(),
            nation: $.trim($('#editNation').val()),
            identity: $.trim($('#editIdentity').val()),
            address: $.trim($('#editAddress').val()),
            wechat: $.trim($('#editWechat').val()),
            remark: $.trim($('#editRemark').val()),
            share: $(this).attr('data-share'),
            areaCode : $('#editVipModel .areaCodeValue').text().trim(),
            vipLevelName: $("#dropdown-level-ul").data('levelName'),
        }
        if(params.name.length == 0){
            $('#edit-vip-info').text(lang('vip.name'));
            return false;
        }
        if(params.mobile.length == 0){
            $('#edit-vip-info').text(lang('vip.mobile'));
            return false;
        }
        if(params.mobile !== '' && !window.commonRegexp.mobile.test(params.mobile)){
            $('#edit-vip-info').text(lang('vip.mobileWrong'));
            return false;
        }
        if(params.identity !== '' && !window.commonRegexp.IDCard.test(params.identity)){
            $('#edit-vip-info').text(lang('vip.identity'));
            return false;
        }
        ajaxRequest('/Home/Customer/editVip', params, 'post', function(data, submitBtn) {
                $('#editVipModel').modal('hide');
                requestInfo(1, '', $('#filterSearch'));
                //更新安装状态
                me.data('edit','0');
            }, function(error, submitBtn, defaultErrorHandler) {
                var errorInfo = error.responseJSON.info;
                $('#edit-vip-info').text(errorInfo); 
        }, me);
       
    });
    
    
    //充值
    var payType = $('#pay-type');
    var rechargeInfo = $('#recharge-vip-info');
    var refillBalance = $('.refill-balance');
    var originalBalance = $('.original-balance');
    var rechargePrice = $('#rechargePrice');
    var rechargeVerification = $('#rechargeVerification');
    var refillRemark = $('#refill-remark');
    $('.rechargeReceiveTypeMenu').on('click','li',function(){
        var submitbtn = $(this); 
        submitbtn.addClass('active').siblings('li').removeClass('active');
        payType.attr('data-value',submitbtn.data('value')).find('.info').text(submitbtn.find('a').text());
    });
    
    rechargePrice.focus(function(){
        rechargeInfo.html('');
    }).blur(function(){
        var value = $(this).val();
        if(window.commonRegexp.roomTypePrice.test(value) &&  rechargePrice.val() != 0){
            var refillPrice = parseFloat(parseFloat(value)+parseFloat(originalBalance.text()));
            refillBalance.text(refillPrice.toFixed(2)).closest('.over').removeClass('hidden');
        }else{
            refillBalance.text('').closest('.over').addClass('hidden');
        }
    });
    $('#rechargeModel').on('show.bs.modal', function(e) {
        var triggerId = $(e.relatedTarget);
        rechargeInfo.html('');
        rechargePrice.val('');
        rechargeVerification.val('');
        refillRemark.val('');
        refreshVcode();
        $('#submitRecharge').data('vipuserid',triggerId.attr('vipUserId')); 
        refillBalance.text('').closest('.over').addClass('hidden');
        var params = {
            hotel: window.currentHotel,
            vipUserId: triggerId.attr('vipUserId')
        }
        ajaxRequest('/Home/Customer/getVipCardRecord', params, 'post', function(data) {
            var info = data.data;
            originalBalance.text(info.price);
            var orderHTML = '';
            if(info.recordInfo.length != 0){
                $.each(info.recordInfo, function (key, orderInfo) {
                    var templateHTML = $($('#templateOrder').clone().html());
                    templateHTML.find('.date').html(orderInfo.createDate.substr(0,10));
                    templateHTML.find('.time').html(orderInfo.createDate.substr(10,10));
                    templateHTML.find('.by').html(orderInfo.payType);
                    templateHTML.find('.operating-info').html(orderInfo.operator);
                    if (orderInfo.type == 0) {
                        if(parseFloat(orderInfo.changePrice)>0){
                            templateHTML.find('.from').html(lang('recharge.1')+'-'+orderInfo.channel);
                            templateHTML.find('.price-info').html(lang('recharge.2')+window.symbols+orderInfo.changePrice+lang('recharge.3')+window.symbols+orderInfo.price);
                        }else{
                            templateHTML.find('.from').html(lang('recharge.4')+'-'+orderInfo.channel);
                            templateHTML.find('.price-info').html(lang('recharge.5')+window.symbols+ (-parseFloat(orderInfo.changePrice)).toFixed(2) +lang('recharge.3')+window.symbols+orderInfo.price);
                        }
                    } else if (orderInfo.type == 1) {
                        templateHTML.find('.from').html(lang('recharge.1')+'-'+orderInfo.channel);
                        templateHTML.find('.price-info').html(lang('recharge.2')+window.symbols+orderInfo.changePrice+lang('recharge.3')+window.symbols+orderInfo.price);
                    } else if (orderInfo.type == 2) {
                        templateHTML.find('.from').html(lang('recharge.4')+'-'+orderInfo.channel);
                        templateHTML.find('.price-info').html(lang('recharge.5')+window.symbols+ orderInfo.changePrice +lang('recharge.3')+window.symbols+orderInfo.price);
                    } else if (orderInfo.type == 3) {
                        templateHTML.find('.from').html(lang('type.refund')+'-'+orderInfo.channel);
                        templateHTML.find('.price-info').html(lang('recharge.14')+window.symbols+ orderInfo.changePrice +lang('recharge.3')+window.symbols+orderInfo.price);
                    }
                    templateHTML.find('.price-info').after('<p>'+orderInfo.remark+'</p>')
                    orderHTML += templateHTML.prop('outerHTML');
                });   
                $('#orderRechargeContainer').html(orderHTML);               
            }else{
                $('#orderRechargeContainer').html(lang('recharge.6'));
            }           
        }, function(error) {
            modalAlert(error.responseJSON.info);
        });        
    });    
    
    $('#submitRecharge').click(function(){
        var submitbtn = $(this);  
        var params = {
            hotel: window.currentHotel,
            vipUserId: submitbtn.data('vipuserid'),
            cardPrice: rechargePrice.val(),
            payType: payType.attr('data-value'),
            remark: refillRemark.val(),
            verify: rechargeVerification.val(),
            share: $(this).data('share'),
        }
        if(!window.commonRegexp.roomTypePrice.test(rechargePrice.val()) || rechargePrice.val()==0){
            rechargeInfo.html(lang('recharge.7'));
            return false;
        }
        if(!window.commonRegexp.vcode.test(rechargeVerification.val())){
            rechargeInfo.html(lang('dealer.verification'));
            return false;
        }
        var confirmPass = window.confirm(lang('recharge.13'));
        if(!confirmPass) {
            return false;
        }        
        ajaxRequest('/Home/Customer/setVipUserCard', params, 'post', function(data) {
            var orderInfo = data.data;
            if($('#orderRechargeContainer').html() == lang('recharge.6')){
                $('#orderRechargeContainer').html('');
            }
            var templateHTML = $($('#templateOrder').clone().html());
            var orderHTML = '';
            templateHTML.find('.date').html(orderInfo.createDate.substr(0,10));
            templateHTML.find('.time').html(orderInfo.createDate.substr(10,10));
            templateHTML.find('.by').html(orderInfo.payType);
            templateHTML.find('.from').html(lang('recharge.1'));
            templateHTML.find('.operating-info').html(orderInfo.operator);
            templateHTML.find('.price-info').html(lang('recharge.2')+orderInfo.changePrice+lang('recharge.3')+orderInfo.price);
            templateHTML.find('.price-info').after('<p>'+orderInfo.remark+'</p>')
            orderHTML += templateHTML.prop('outerHTML');  
            $('#orderRechargeContainer').prepend(orderHTML);
            rechargeInfo.html('');
            rechargePrice.val('');
            rechargeVerification.val('');
            refillRemark.val('');
            originalBalance.text(orderInfo.price);
            refillBalance.text('').closest('.over').addClass('hidden');
            refreshVcode();
        }, function(error) {
            refreshVcode();
            var errorInfo = error.responseJSON.info;
            rechargeInfo.text(errorInfo); 
        }, submitbtn);
    });      
    $('#rechargeModel').on('hide.bs.modal', function(e) {
        var value = 0;
        $('#customerListPage .pagination li').each(function(){
            if($(this).hasClass('active')){
                value = $(this).find('a').data('value');
            }
        });
        requestInfo(value, '', $('#filterSearch'));
    });    
})